const testMode = false; // 为true时可以在浏览器打开不报错
// vscode webview 网页和普通网页的唯一区别：多了一个acquireVsCodeApi方法
const vscode = testMode ? {} : acquireVsCodeApi();
const callbacks = {};

/**
 * 调用vscode原生api
 * @param data 可以是类似 {cmd: 'xxx', param1: 'xxx'}，也可以直接是 cmd 字符串
 * @param cb 可选的回调函数
 */
function callVscode(data, cb) {
    if (typeof data === 'string') {
        data = { cmd: data };
    }
    if (cb) {
        // 时间戳加上5位随机数
        const cbid = Date.now() + '' + Math.round(Math.random() * 100000);
        callbacks[cbid] = cb;
        data.cbid = cbid;
    }
    vscode.postMessage(data);
}

window.addEventListener('message', event => {
    const message = event.data;
    switch (message.cmd) {
        case 'vscodeCallback':
            console.log(message.data);
            (callbacks[message.cbid] || function () { })(message.data);
            delete callbacks[message.cbid];
            break;
        default: break;
    }
});

// Vue 3 应用
const { ref, onMounted, reactive } = window.Vue

const App = {
    setup() {
        // 响应式状态
        const accounts = ref([]);
        const config = ref(null);
        const currentAccount = ref(null);
        const createVisible = ref(false);
        const editEnv = ref(null);
        const browsers = ref([
            { label: 'Chrome', value: 'Google Chrome' },
            { label: 'Firefox', value: 'Firefox' },
            { label: 'Safari', value: 'Safari' },
            { label: 'Arc', value: 'Arc' },
        ]);
        const form = reactive({
            env: '',
            domain: '',
            loginId: '',
            password: '',
            vendor: '',
            emailLogin: false,
            host: '',
            port: '',
            url: '',
            browser: '',
          })
        const formRef = ref(null);
        const rules = reactive({
            env: [{ required: true, message: '请输入环境', trigger: 'blur' }],
            domain: [{ required: true, message: '请输入域名', trigger: 'blur' }],
            loginId: [{ required: true, message: '请输入登录ID', trigger: 'blur' }],
            password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
            
        })
        const importText = ref('');
        const importVisible = ref(false);
        const activeEnvs = ref([]);
        // 方法
        const getConfig = (key, cb) => {
            callVscode({ 
                cmd: 'getConfig', 
                key: key 
            }, config => {
                cb && cb(config);
            });
        };

        const saveConfig = (key, value) => {
            callVscode({ 
                cmd: 'saveConfig', 
                key: key,
                value: value 
            }, result => {
                if (result) {
                    alert('配置保存成功');
                }
            });
        };

        const alert = (info) => {
            callVscode({ cmd: 'alert', info: info }, null);
        };

        const error = (info) => {
            callVscode({ cmd: 'error', info: info }, null);
        };


        const refreshLogin = (data) => {
            alert('开始修改文件并刷新登录');
            callVscode({cmd: 'refreshLogin', data: JSON.stringify(data)}, () => {
                alert('刷新登录成功');
            });
            currentAccount.value = data;
        };

        const prodLogin = (data) => {
            alert('开始生产环境登录');
            callVscode({cmd: 'prodLogin', data: JSON.stringify(data)}, () => {
                alert('生产环境登录成功');
            });
        };

        const addAccount = async () => {
            createVisible.value = true;
        };

        const activeStyle = (data) => {
            if (!currentAccount.value) {
                return { flex: 1 };
            }

            const { env, domain, loginId } = currentAccount.value;
            
            return {
                color: (env === data.env && domain === data.domain && loginId === data.loginId) ? 'red' : '',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                flex: 1,
            };
        };

        const activeEnvStyle = (data) => {
            return {
                color: (currentAccount.value?.env === data.env) ? 'red' : '',
            };
        }

        const editAccount = (data) => {
            editEnv.value = {...data};  // 复制一份数据
            createVisible.value = true;
            // 重置表单数据
            Object.keys(form).forEach(key => {
                form[key] = data[key] || '';
            });
        };

        const onConfirm = async (formEl) => {
            await formEl.validate((valid) => {
                if (valid) {
                    // 创建一个新的对象而不是直接使用form引用
                    const formData = {...form};

                    if (editEnv.value) {
                        accounts.value = accounts.value.map(item => {
                            if (item.env === editEnv.value.env) {
                                item.children = item.children.map(child => 
                                    child.domain === editEnv.value.domain && 
                                    child.loginId === editEnv.value.loginId ? 
                                    formData : child
                                );
                            }
                            return item;
                        });
                    } else {
                        // 检查是否存在相同的账号
                        const accountExists = accounts.value.some(item => 
                            item.env === formData.env && 
                            item.children.some(child => 
                                child.domain === formData.domain && 
                                child.loginId === formData.loginId
                            )
                        );
                        
                        if (accountExists) {
                            error('已存在相同的账号，请检查环境、域名和登录ID');
                            return;
                        }
                        const curEnv = accounts.value.find(item => item.env === formData.env);
                        if (curEnv) {
                            curEnv.children.push(formData);
                        } else {
                            accounts.value.push({
                                env: formData.env, 
                                children: [formData]
                            });
                        }
                    }
                    
                    saveConfig('webLoginPlugin.accounts', JSON.stringify(accounts.value));
                    createVisible.value = false;
                    formRef.value.resetFields();
                    editEnv.value = null;  // 重置编辑状态
                }
            });
        };

        const deleteAccount = (data) => {
            accounts.value = accounts.value.filter(item => {
                if (item.env === data.env) {
                    item.children = item.children.filter(child => child.domain !== data.domain || child.loginId !== data.loginId);
                    return item.children.length > 0;
                }
                return true;
            });
            saveConfig('webLoginPlugin.accounts', JSON.stringify(accounts.value));
        };

        const onClose = () => {
            createVisible.value = false;
            formRef.value.resetFields();
            Object.keys(form).forEach(key => form[key] = '');
            editEnv.value = null;  // 重置编辑状态
        };

        const onImportConfirm = () => {
            try {
                const importData = JSON.parse(importText.value);
                if (Array.isArray(importData)) {
                    // 遍历导入的数据
                    importData.forEach(importEnv => {
                        // 查找是否存在相同env的环境
                        let existingEnv = accounts.value.find(acc => acc.env === importEnv.env);
                        
                        if (!existingEnv) {
                            // 如果环境不存在，直接添加
                            accounts.value.push(importEnv);
                        } else {
                            // 如果环境存在，遍历其children
                            importEnv.children.forEach(importChild => {
                                // 检查是否存在相同的账号（通过env、domain和loginId判断）
                                const exists = existingEnv.children.some(existingChild => 
                                    existingChild.env === importChild.env && 
                                    existingChild.domain === importChild.domain && 
                                    existingChild.loginId === importChild.loginId
                                );
                                
                                // 如果不存在，则添加到对应环境的children中
                                if (!exists) {
                                    existingEnv.children.push(importChild);
                                }
                            });
                        }
                    });
                    
                    saveConfig('webLoginPlugin.accounts', JSON.stringify(accounts.value));
                    importVisible.value = false;
                    importText.value = '';
                    alert('导入成功');
                } else {
                    error('导入数据格式错误，请确保是正确的账号数据');
                }
            } catch (e) {
                error('导入数据解析失败，请确保是有效的JSON格式');
            }
        };

        const exportAccounts = () => {
            // 将账户数据复制到剪贴板
            const accountsData = JSON.stringify(accounts.value, null, 2);
            navigator.clipboard.writeText(accountsData)
                .then(() => {
                    alert('账户数据已成功复制到剪贴板');
                })
                .catch(err => {
                    error('复制到剪贴板失败: ' + err);
                });
        }

        const copyLogin = (data) => {
            navigator.clipboard.writeText(JSON.stringify(data))
                .then(() => {
                    alert('登录信息已成功复制到剪贴板');
                })
                .catch(err => {
                    error('复制到剪贴板失败: ' + err);
                });
        }
        
        const importAccount = () => {
            // 从剪贴板读取数据
            navigator.clipboard.readText()
                .then(text => {
                    try {
                        const data = JSON.parse(text);
                        // 将解析后的数据复制到form对象
                        Object.keys(form).forEach(key => {
                            if (data[key] !== undefined) {
                                form[key] = data[key];
                            }
                        });
                        alert('账号信息已成功导入到表单');
                    } catch (e) {
                        error('解析JSON数据失败，请确保格式正确');
                    }
                })
                .catch(err => {
                    error('从剪贴板读取失败: ' + err);
                });
        }

        const importAccounts = () => {
            // 从剪贴板读取账户数据
            importVisible.value = true;
        }

        const topEnv = (env) => {
            const idx = accounts.value.findIndex(item => item.env === env);
            if (idx > 0) {
                const [item] = accounts.value.splice(idx, 1);
                accounts.value.unshift(item);
                // 可选：保存配置
                saveConfig('webLoginPlugin.accounts', JSON.stringify(accounts.value));
            }
        };

        const handleDropdownCommand = (command) => {
            if (command === 'import') {
                importAccounts();
            } else if (command === 'export') {
                exportAccounts();
            }
        };

        // 生命周期钩子
        onMounted(() => {
            getConfig('webLoginPlugin.accounts', (v) => {
                if (!v) return
                accounts.value = JSON.parse(v).map(env => {
                    env.children = env.children.map(child => ({ ...child, env: env.env }))
                    return env
                })
            });
            callVscode({cmd: 'getCurrentAccount'}, (v) => {
                currentAccount.value = v;
                activeEnvs.value = [ v.env ];
            });
        });

        // 暴露到模板
        return {
            accounts,
            config,
            createVisible,
            form,
            formLabelWidth: '60px',
            formRef,
            rules,
            browsers,
            editEnv,
            activeEnvs,
            activeEnvStyle,
            getConfig,
            saveConfig,
            editAccount,
            deleteAccount,
            alert,
            error,
            refreshLogin,
            prodLogin,
            activeStyle,
            addAccount,
            onConfirm,
            onClose,
            exportAccounts,
            importAccounts,
            importText,
            importVisible,
            onImportConfirm,
            copyLogin,
            importAccount,
            topEnv,
            handleDropdownCommand,
        };
    }
};

// 创建Vue应用
const app = Vue.createApp(App);

// 注册所有图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
}

// 使用Element Plus
app.use(ElementPlus);

// 挂载应用
app.mount('#app');